package locate

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
	"time"
	"tsuhi_api_server/conf"
	"tsuhi_api_server/mqs/rabbitmq"
)

var config *conf.Config

func init() {
	config = conf.StorageRoot()
}

func Handler(w http.ResponseWriter, r *http.Request) {

	method := r.Method
	if method == http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	info := Locate(strings.Split(r.URL.EscapedPath(), "/")[2])
	if len(info) == 0 {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	marshal, _ := json.Marshal(info)
	w.Write(marshal)
}

func Locate(name string) string {
	mq := rabbitmq.New(config.Server.RabbitServer)
	mq.Publish("dataServer", name)
	consume := mq.Consume()
	go func() {
		time.Sleep(time.Second)
		mq.Close()
	}()
	msg := <-consume
	s, _ := strconv.Unquote(string(msg.Body))
	return s
}

func Exist(name string) bool {

	return Locate(name) != ""
}
